//
//  ChatItemBotView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/5/2.
//

import SwiftUI
import Kingfisher

struct ChatItemBotView: View {
    @ObservedObject var viewModel: ChatViewModel
    @State var item: ChatBean
    @State private var showDel = false //删除
    @State private var showVoice = false //语音
    @State private var showVoice2 = false //语音
    @State private var showEdit = false
    @State private var hignBg = false //高亮背景
    @State var isStartedSound:Bool = false  //语音播放
    @State var convertText: Bool = false //语音转为文本
    @State private var select = false //选中
    let clickEdit: (Bool) -> Void

    var body: some View {
        HStack(alignment:.top, spacing: 10) {
            if viewModel.choose {
                chooseView
            }
            ChatAvatarVeiw(item: item)
            VStack(alignment: .leading) {
                contentView
                    .overlay(alignment: .bottomTrailing) {
                        //需要文本类型才显示
                        //语音标识，改类型是文字转为语音，所以需要TYPE_CONTENT 类型才行
                        if IChatContentType.TYPE_CONTENT.rawValue == item.contentType && viewModel.voiceStatus >= 0 && item.voicePath?.isEmpty == false {
                            Image(.homeIconPlay)
                                .resizable()
                                .renderingMode(.template)
                                .scaledToFill()
                                .foregroundColor(themeManager.themeColor)
                                .padding(7)
                                .frame(width: 30, height: 30)
                                .background(themeManager.themeColor.opacity(0.3))
                                .clipShape(Circle())
                                .padding(.trailing, 45)
                                .offset(x: 15, y: 15) // 向右下偏移
                                .onTapGesture {
                                    viewModel.doVoice(bean: item,isStarted: $isStartedSound)
                                }
                        }
                    }
                //语音转为文本
                if convertText == true {
                    ChatConvertTextView(bean: item)
                }
                //引用内容
                if let target = item.targetChat {
                    ChatTargetView(bean: target)
                }
                //                Text("消费1000token")
                //                    .font(.system(size: 10))
                //                    .foregroundStyle(.bgNormalText4)
                //                    .padding(.horizontal,10)
                //                    .padding(.top,1)
            }
        }.frame(maxWidth: .infinity,alignment: .topLeading)
            .padding(EdgeInsets(top: 10, leading: 15, bottom: 20, trailing: 15))
            .background {
                if hignBg {
                    themeManager.themeColor.opacity(0.2)
                }
            }.contextMenu {
                if !viewModel.choose {
                    commonMenuContent
                }
            }
            .alert("温馨提示",isPresented:$showDel) {
                Button("取消",role: .cancel){}
                Button("确定",role: .destructive) {
                    viewModel.delChat(bean: item)
                }
            } message: {
                Text("是否确定要删除")
            }.alert("温馨提示",isPresented:$showVoice2) {
                Button("转文字",role: .cancel){
                    onClickMenu(7)
                }
                Button("播放",role: .destructive) {
                    viewModel.doVoice(bean: item,isStarted: $isStartedSound)
                }
            } message: {
                Text("播放语音需消耗 2次回应次数，是否继续？")
            }.alert("温馨提示",isPresented:$showVoice) {
                Button("取消",role: .cancel){}
                Button("播放",role: .destructive) {
                    viewModel.doVoice(bean: item,isStarted: $isStartedSound)
                }
            } message: {
                Text("播放语音需消耗 2次回应次数，是否继续？")
            }.onReceive(viewModel.$scrollChat.dropFirst()) { value in
                if value == item.objectId {
                    //搜索id一致，则高亮
                    withAnimation {
                        hignBg = true
                    }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                        withAnimation {
                            hignBg = false
                        }
                    }
                }
            }
            .onChange(of: select) { newValue in
                item.select = newValue
            }
            .overlay {
                if viewModel.choose {
                    Color.clear
                        .contentShape(Rectangle())
                        .onTapGesture {
                            select = !select
                        }
                }
            }
    }
}
extension ChatItemBotView {
    var contentView : some View {
        ZStack {
            if getBubble() != nil {
                //需要加id，不然刷新文字无法更新
                BubbleChatView2(str: item.content ?? "",sound: item.getSound(), bean: getBubble() ?? BubbleBean(),isStartedSound: $isStartedSound) {
                    doVoice2()
                }.id(item.content)
            } else {
                ZStack {
                    if let sound = item.getSound() {
                        ChatItemVoiceView(bean: sound, color: .bgNormalText, isStarted: $isStartedSound) {
                            doVoice2()
                        }
                    } else {
                        Text(item.content ?? "")
                            .font(.system(size: 14))
                            .foregroundStyle(.bgNormalText)
                    }
                }.padding(.horizontal, 10)
                    .padding(.vertical, 5)
                    .frame(minHeight: 40).frame(minWidth: 40)
                    .background(.bgItem)
                    .cornerRadius(10)
                    .padding(.trailing, 35)
            }
        }
    }
    
    func getBubble() -> BubbleBean?{
        let id = item.role?.bubbleId ?? ""
        return BubbleExt.getBubble(id: id)
    }
    
    func doVoice() {
        if (item.voicePath ?? "").isEmpty == true {
            showVoice = true
        } else {
            viewModel.doVoice(bean: item,isStarted: $isStartedSound)
        }
    }
    
    func doVoice2() {
        if (item.voicePath ?? "").isEmpty == true {
            showVoice2 = true
        } else {
            viewModel.doVoice(bean: item,isStarted: $isStartedSound)
        }
    }
}
extension ChatItemBotView {
    //多选试图
    private var chooseView: some View {
        Group {
            if select == true {
                Image(.appIcCheckboxSelect)
                    .resizable()
                    .renderingMode(.template)
                    .foregroundColor(themeManager.themeColor)
                    .frame(width: 20,height: 20)
                    .padding(.top, 10)
            } else {
                Image(.appIcCheckbox)
                    .resizable()
                    .frame(width: 20,height: 20)
                    .padding(.top, 10)
            }
        }.onAppear{
            select = item.select ?? false
        }
    }
}

extension ChatItemBotView {
    // 将菜单内容抽离为一个计算属性，方便复用
    private var commonMenuContent: some View {
        Group {
            if item.contentType == IChatContentType.TYPE_VOICE_MESSAGE.rawValue {
                Button("撤回") {
                    onClickMenu(0)
                }
                Button("装扮气泡") {
                    onClickMenu(4)
                }
                Button("引用") {
                    onClickMenu(6)
                }
                Button("转文字") {
                    onClickMenu(7)
                }
                Button("播放语音") {
                    onClickMenu(8)
                }
                Button("多选") {
                    onClickMenu(9)
                }
            } else {
                Button("删除") {
                    onClickMenu(0)
                }
                Button("语音") {
                    onClickMenu(1)
                }
                Button("编辑") {
                    onClickMenu(2)
                }
                Button("复制") {
                    onClickMenu(3)
                }
                Button("装扮气泡") {
                    onClickMenu(4)
                }
                Button("引用") {
                    onClickMenu(6)
                }
                Button("多选") {
                    onClickMenu(9)
                }
            }
            
        }
    }
    
    func onClickMenu(_ type:Int) {
        hideKeyboard()
        switch(type) {
        case 0: //删除
            showDel = true
            break
        case 1://语音
            doVoice()
            break
        case 2://编辑
            clickEdit(true)
            showEditDialog(title: "编辑内容",hint: "请重新输入内容", content: item.content ?? "") { it in
                clickEdit(false)
                if !(it ?? "").isEmpty {
                    item.content = it
                    viewModel.saveChat(bean: item)
                }
            }
            break
        case 3://复制
            showToast("复制成功")
            copyClipboard(item.content)
            break
        case 4://装扮气泡
            pathManager.jump(type: JumpType.BUBBLE_MY,data: item.role?.roleId ?? "")
            break
        case 5:
            pathManager.jump(type: JumpType.BUBBLE_MY,data: item.role?.roleId ?? "")
            break
        case 6://引用
            if !AppStorageManager.shared.checkChatFuncToggle() {
                return
            }
            viewModel.targetChatBean = item
            break
        case 7://转文字
            convertText = true
            break
        case 8://播放语音
            doVoice2()
            break
        case 9://多选模式
            viewModel.setChooseMode()
            break
        default:
            break
        }
    }
}

#Preview {
    ChatItemBotView(viewModel: ChatViewModel(),item: ChatBean()){clickEdit in}.background(.bg)
}
